package com.wzh.project.utils.ssh2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
*@author : 汪振海
*@createdDate : Jan 3, 2020  9:14:18 AM
*@description : 执行服务器所在机器的工具类<br>
*
*/
public class LocalCmdUtils {
	
	private static final Logger logger = LogManager.getLogger(LocalCmdUtils.class);
	
	/**
	 * 执行多条cmd命令 命令中间使用&&进行分割，不支持含有特殊符号的祝贺命令（默认当前路径为程序运行路径）
	 * @param cmds
	 * @return
	 */
	public static String runLocalCmd(String cmds) {
		String[] cmd = cmds.split("&&");
		StringBuffer result=new StringBuffer();
		for (int i = 0; i < cmd.length; i++) {
			result.append("命令："+cmd[i]+" 执行的结果为:"+runSingleCmd(cmd[0])+"\r");
		}
		return result.toString();
	}
	/**
	 * 只能一条一条执行
	 * 运行程序所在的工具类
	 * @param cmd
	 * @return
	 */
	public static String runSingleCmd(String command) {
		    StringBuffer returnString = new StringBuffer();
	        Process pro = null;
	        Runtime runTime = Runtime.getRuntime();
	        if (runTime == null) {
	        	logger.error("Create runtime false!");
	        }
	        try {
	            pro = runTime.exec(command);
	            BufferedReader input = new BufferedReader(new InputStreamReader(pro.getInputStream()));
	            PrintWriter output = new PrintWriter(new OutputStreamWriter(pro.getOutputStream()));
	            String line;
	            while ((line = input.readLine()) != null) {
	                returnString.append(line + "\n");
	            }
	            input.close();
	            output.close();
	            pro.destroy();
	        } catch (IOException ex) {
	        	logger.error(ex);
	        }
	        return returnString.toString();
	    }
	
	public static String run(String[] command) throws IOException {
		Scanner input = null;
		String result = "";
		Process process = null;
		try {
			process = Runtime.getRuntime().exec(command);
			try {
				//等待命令执行完成
				process.waitFor(10, TimeUnit.SECONDS);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			InputStream is = process.getInputStream();
			input = new Scanner(is);
			while (input.hasNextLine()) {
				result += input.nextLine() + "\n";
			}
			result = command + "\n" + result; //加上命令本身，打印出来
		} finally {
			if (input != null) {
				input.close();
			}
			if (process != null) {
				process.destroy();
			}
		}
		return result;
	}

}
